package com.sample.library

import android.net.http.SslError
import android.os.Bundle
import android.view.View
import android.webkit.SslErrorHandler
import android.webkit.WebView
import android.widget.LinearLayout
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar
import com.just.agentweb.AgentWeb
import com.just.agentweb.AgentWebConfig
import com.just.agentweb.WebChromeClient
import com.just.agentweb.WebViewClient
import com.sample.library.web.AgentWebHelper
import com.sample.library.web.AndroidInterface
import com.sample.library.web.CollectEvent
import com.sample.library.web.SwipeRefreshWebLayout
import org.greenrobot.eventbus.EventBus

open class WebActivity : BasicActivity() {

    var s: String? = null

    var t: String? = null

    private var url: String? = null
    private var title: String? = null
    private var author: String? = null
    private var collect = false

    private var mAgentWeb: AgentWeb? = null

    private var swipeRefreshWebLayout: SwipeRefreshWebLayout? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)



        setContentView(R.layout.activity_agentweb)

        url = intent.getStringExtra("url")
        title = intent.getStringExtra("title")
        author = intent.getStringExtra("author")
        collect = intent.getBooleanExtra("collect", false)

        val viewgroup = findViewById<LinearLayout>(R.id.linearLayout)
        swipeRefreshWebLayout = SwipeRefreshWebLayout(this)
        findViewById<TitleBar>(R.id.titleBar).apply {
            if (title == null) {
                title = "Sample"
            }
            title = title
            author?.let {
                rightTitle = "收藏"
            }
            setOnTitleBarListener(titleBarListener)
        }
        swipeRefreshWebLayout?.layout?.setOnRefreshListener { mAgentWeb?.urlLoader?.reload() }
        mAgentWeb = AgentWebHelper.getAgentWeb(this, viewgroup, swipeRefreshWebLayout, url, webViewClient, webChromeClient)
        mAgentWeb?.webCreator?.webView?.overScrollMode = WebView.OVER_SCROLL_IF_CONTENT_SCROLLS
        mAgentWeb?.jsInterfaceHolder?.addJavaObject("imagelistener", AndroidInterface(this, arrayOf()))
        AgentWebConfig.debug()
    }

    private val webViewClient = object : WebViewClient() {
        override fun onPageFinished(view: WebView?, url: String?) {
            swipeRefreshWebLayout?.layout?.isRefreshing = false
            super.onPageFinished(view, url)
            addImageClickListener(view)
        }

        override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler, error: SslError?) {
            handler.proceed()
            super.onReceivedSslError(view, handler, error)
        }

        //通过js代码找到标签为img的代码块，设置点击的监听方法与本地的openImage方法进行连接
        private fun addImageClickListener(webView: WebView?) {
            webView?.loadUrl("javascript:(function(){" + "var objs = document.getElementsByTagName(\"img\"); " + "for(var i=0;i<objs.length;i++)  " + "{" + "    objs[i].onclick=function()  " + "    {  " + "        window.imagelistener.openImage(this.src);  " + "    }  " + "}" + "})()")
        }
    }

    private val webChromeClient = object : WebChromeClient() {
        override fun onReceivedTitle(view: WebView?, title: String?) {
            title?.let { findViewById<TitleBar>(R.id.titleBar).setTitle(it) }
            super.onReceivedTitle(view, title)
        }
    }

    private val titleBarListener = object : OnTitleBarListener {

        override fun onLeftClick(v: View?) {
            mAgentWeb?.apply {
                if (!back()) {
                    finish()
                }
            }
        }

        override fun onTitleClick(v: View?) {
            mAgentWeb?.webCreator?.webView?.scrollTo(0, 0)
        }

        override fun onRightClick(v: View?) {
            mAgentWeb?.apply {
                v?.visibility = View.GONE
                EventBus.getDefault().post(CollectEvent(url, title, author))
            }
        }
    }

    override fun onBackPressed() {
        mAgentWeb?.apply {
            if (!back()) {
                super.onBackPressed()
            }
        }
    }

    override fun onResume() {
        mAgentWeb?.webLifeCycle?.onResume()
        super.onResume()
    }

    override fun onPause() {
        mAgentWeb?.webLifeCycle?.onPause()
        super.onPause()
    }

    override fun onDestroy() {
        mAgentWeb?.webLifeCycle?.onDestroy()
        super.onDestroy()
    }
}

